package com.zhima.config;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.zhima.properties.AliyunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(AliyunSmsProperties.class)
public class AliyunSmsConfiguration {
    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    @Bean
    public IAcsClient getClient() {
        IClientProfile profile = DefaultProfile.getProfile(
                aliyunSmsProperties.getRegionId(),
                aliyunSmsProperties.getAccessKeyId(),
                aliyunSmsProperties.getAccessKeySecret());
        try {
            DefaultProfile.addEndpoint(aliyunSmsProperties.getEndpointName(),
                    aliyunSmsProperties.getRegionId(),
                    aliyunSmsProperties.getProduct(),
                    aliyunSmsProperties.getDomain());
        } catch (ClientException e) {
            log.error("获取短信发送服务机发生错误。错误代码是 [{}]，错误消息是 [{}]，错误请求ID是 [{}]，错误Msg是 [{}]，错误类型是 [{}]",
                    e.getErrCode(),
                    e.getMessage(),
                    e.getRequestId(),
                    e.getErrMsg(),
                    e.getErrorType());
        }
        return new DefaultAcsClient(profile);
    }
}
